package com.kws.commercial.business;

import com.kws.commercial.util.MinioAPI;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.config.util.DateTimeUtil;
import com.kws.common.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;

/**
 * <b>UploadFileBusiness</b>
 *
 * @description: UploadFileBusiness <br>
 * @date: 2024/10/29 17:15 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Component
public class UploadFileBusiness {
    private static final Logger logger = LoggerFactory.getLogger(UploadFileBusiness.class);

    @Autowired
    private MinioAPI minioAPI;

    private final static String SLASH = "/";

    private final static String FILE_NAME_PREFIX_SEPARATOR = "-";

    @Value("${minio.ENDPOINT}")
    private String minioUrl;

    public String uploadFile(MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            String bucketName = MinioCommonBucket.HUATAI_PUB_BUCKET;
            String objectKey = getObjectKey(file.getSize(), file.getOriginalFilename());
            minioAPI.uploadInputStream(bucketName, objectKey, is, file.getContentType());
            logger.info("上传地址为:{}"+objectKey);
            return minioUrl+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET+"/"+objectKey;
        } catch (Exception e) {
            logger.error("上传失败，", e);
            throw new ServiceException("上传失败，请重新上传");
        }
    }

    private String getObjectKey(Long fileSize,String fileName) {
        String date = DateTimeUtil.format(LocalDate.now(),"yyyyMMdd");

        StringBuilder objectKey = new StringBuilder(date);
        objectKey.append(SLASH).append(fileSize).append(FILE_NAME_PREFIX_SEPARATOR).append(fileName);
        return objectKey.toString();
    }
}
